package lib.modules;

import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

import lib.base.EgoException;
import lib.base.EgoHoliday;
import lib.base.EgoModule;

public class EventGadget extends EgoModule
{
	public EventGadget(HttpServletRequest req)
	{
		super(req);
		req.getSession().setAttribute("template", "modules/event/frame.jsp");
	}
	
	@Override
	public void work() throws Exception
	{
		// ajax request
		if (_request.getParameter("action") != null)
		{
			_doAction();
		} else
		{
			_setParams();
		}
	}
	
	private void _doAction() throws Exception
	{
		if (_request.getParameter("action").equals("new"))
		{
			// extract Data
			String[] x1 = _request.getParameter("data").split(",");
			EgoHoliday holiday = new EgoHoliday(_curEmp);
			
			if (x1.length == 2)
			{
				holiday.setStartStamp(x1[0]);
				if (x1[1].equals( "half" ))
				{
					holiday.setEndStamp(x1[0]);
					holiday.setHalfDay(true);
				} else
				{
					holiday.setEndStamp(x1[1]);
				}
			} else
			{
				throw new EgoException(EgoException.WRONG_HOLIDAY_SYNTAX);
			}
			_curCust.holidayManager.newHoliday(holiday);
			
			_request.setAttribute("ajax_return", "Leave successfully requested.");
			_request.getSession().setAttribute("template", "ajax_return.jsp");
		}	
	}
	
	private void _setParams() throws Exception
	{
		// year
		String year =  _request.getParameter("date").toString().substring(0, 4);
		ArrayList<EgoHoliday> allHolidays = _curCust.holidayManager.getHolidays(_curEmp, year);
		float remaining = _curCust.holidayManager.getRemainingLeaves(_curEmp, allHolidays);
		
		// if future - no remaining leaves from prev year
		Calendar cal = Calendar.getInstance();
		int cur_year = cal.get(Calendar.YEAR); // current year
		if (cur_year != Integer.parseInt(year))
		{
			remaining -= Float.parseFloat( _curEmp.getField("remainingLeavePrevYear").toString() );
		}
		
		_request.setAttribute("remainingLeave", remaining);
		_request.setAttribute("entitlementLeave",
			Float.parseFloat(_curEmp.getField("entitlementLeave").toString())
			+ (cur_year != Integer.parseInt(year) ? 0 : Float.parseFloat(_curEmp.getField("remainingLeavePrevYear").toString()))
		);
		_request.setAttribute("workingDays", _curEmp.getField("workingDays"));
		_request.setAttribute("allHolidays",
			allHolidays
		);
		_request.setAttribute("allPublicHolidays",
			_curCust.holidayManager.getPublicHolidays(_curEmp, year)
		);
	}
}
